/**
 * @desc:商户账单显示
 * @author:elvis
 */
import { useState, useEffect, useMemo } from "react";
import { useNavigate } from 'react-router-dom';
import PayModal from "@/pages/AccountModule/accountSafety/component/PayModal/PayModal";
import BankCardModal from "@/pages/AccountModule/accountSafety/component/BankCardModal/BusinessBindModal";
import RechargeModal from "../component/RechargeModal/index";
import TransferModal from "../component/TransferModal/index";
import ScanRechargeModal from "../component/ScanRechargeModal/index";
import CommonLoading from "@/components/CommonLoading";
import { Button, Modal, message } from "antd";
import { getDifferUserDetails } from '@/utils/authority';
import { formatAmount } from '@/utils/utils.jsx';
import IconFont from "@/components/IconFont";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { getAccountBalanceOp, checkSellerStatus, cancelCard  } from '../../service';
import styles from "./index.module.less";

let timer = undefined;

const UserInfo = ({ type, accountMsg, infoKey, balanceKey, dispatch }) => {

	//用于展示的用户信息
	const [accountDetail, setAccounrDetail] = useState({});
	const navigate = useNavigate();

	const { merchantNo, userType } = accountMsg;
	
	//控制按钮操作的弹框
	const [visible, setVisible] = useState(undefined);

	//可用余额显隐状态
	const [canUseAmount, setCanUse] = useState(true);

	//提现待到账金额显隐状态
	const [awaitAmount, setAwait] = useState(true);

	//待结算显隐状态
	const [pendingAmount, setPending] = useState(true);

	const [loading, setLoading] = useState(false);

	const currentUser = useMemo(()=>{
		return getDifferUserDetails()
	}, []);

	const computeShowAmount = useMemo(()=>{
		if(Object.keys(accountDetail).length){
			const { settlementAmountBal, creditSettlementAmountBal } = accountDetail;
      return (Math.round(Number(settlementAmountBal) * 1000) + Math.round(Number(creditSettlementAmountBal) * 1000)) / 1000;
		}
	}, [accountDetail]);

	//获取用户信息
	const getAccountInfo = async () => {
		setLoading(true);
		const User = checkSellerStatus({ accountNo: merchantNo });
		const Balance = getAccountBalanceOp({ accountType: type });
		const res = await Promise.all([User, Balance]);
		const obj = {};
		const userMsg = res[0];
		const balanceMsg = res[1];
		setLoading(false);
		if (userMsg.success) {
			const userData = userMsg.data;
			obj.mobile = currentUser.mobile;
			obj.hasPassword = userData.hasPassword;//是否设置了密码
			obj.bankNo = userData.bankinfo.bankNo;//银行卡号
			obj.openBankName = userData.bankinfo.openBankName;//开户行名称
			obj.bankMobile = userData.bankinfo.mobile;//开户行手机号码
			obj.name = userData.bankinfo.name;//持卡人姓名
		}

		if (balanceMsg.success) {
			const balanceData = balanceMsg.data;
			obj.availBalance = balanceData.availBalance;//可用余额
			obj.cashBalance = balanceData.cashBalance;//提现待到账金额
			obj.settlementAmountBal = balanceData.settlementAmountBal;//余额待结算
			obj.creditSettlementAmountBal = balanceData.creditSettlementAmountBal;//账期待结算

			obj.hasOpenAccount = balanceData.hasOpenAccount;
		}
		setAccounrDetail(obj);
	}

	useEffect(() => {
		getDataDebounce();
	}, [infoKey, balanceKey])

	const getDataDebounce = () => {
		if(timer) {
			clearTimeout(timer);
			timer = setTimeout(() => {
				getAccountInfo();
				clearTimeout(timer);
				timer = undefined;
			}, 200);
		} else {
			timer = setTimeout(() => {
				getAccountInfo();
				clearTimeout(timer);
				timer = undefined;
			}, 200);
		}
	}

	//点击修改/设置密码
	const handlePasswordClick = () => {
		if (currentUser.parentId) {
			Modal.info({
				content: '子账号不允许设置、修改支付密码'
			})
			return;
		}
		setVisible('updatePassword');
	}

	//点击解绑和绑卡
	const handleClickBank = () => {
		if(accountDetail.bankNo) {
			//代表已经绑卡，是要去解绑
			Modal.confirm({
				title: '提示',
				icon: <ExclamationCircleOutlined />,
				content: '银行卡解绑后不能余额提现，确定要解绑吗？',
				onOk() {
					cancelBank();
				},
			});
		} else {
			//去绑卡
			setVisible('updateBank');
		}
	}

	//解除绑定
	const cancelBank = async () => {
		const { success, data } = await cancelCard({
			accountNo: merchantNo,
			accountType: 2,
		});
		if (success) {
			message.success('银行卡解绑成功');
			getAccountInfo();
		}
	}

	//充值公共点击（扫码 普通充值）
	const commonRechargeClick = (type) => {
		if (!accountDetail.hasOpenAccount) {
			Modal.info({
				title: "温馨提示",
				content: "您还未开户，请先完成开户再来操作",
			});
			return
		}
		setVisible(type);
	}
	
	//点击申请提现、转账充值
	const commonCheckAccountAndBank = (type) => {
		if(type == 'applyCash' && !parseFloat(availBalance)){
			Modal.info({
				title: '温馨提示',
				content:'当前可提现余额为0， 不可提现',
			})
			return ;
		}
		if (!accountDetail.hasOpenAccount) {
			return Modal.info({
				title: "温馨提示",
				content: "您还未开户，请先完成开户再来操作",
			});
		}
		if (!accountDetail.bankNo) {
			return Modal.confirm({
				title: "绑卡提示",
				content: "您还没有绑定银行卡，无法进行转账充值！",
				okText: "去绑卡",
				onOk() {
					setVisible('updateBank');
				},
			});
		}
		if(type == 'applyCash'){
			navigate('/account/applyCash', {
				state: {
					accountNo: merchantNo
				}
			})
		}else{
			setVisible('transferCharge');
		}
	};

	//支付密码modal
	const PayModalProps = {
		PayModalSwitch: true,
		personageMessage: { 
			...accountDetail,
			accountNo: accountMsg.accountNo,
		},
		PayModalOk() {
			setVisible(undefined);
			getAccountInfo();
		},
		PayModalNo() {
			setVisible(undefined);
		},
	};

	// 普通充值modal
	const RechargeModalProps = {
		accountMsg,
		visible: true,
		handleVisible(val) {
			setVisible(val);
			dispatch({
				type: 'add'
			})
		},
		reloadFunc() {
			dispatch({
				type: 'add'
			})		
		}
	};

	//扫码充值modal
	const ScanRechargeModalProps = {
		accountMsg,
		handleVisible() {
			setVisible(false);
		},
		reloadFunc(){
			dispatch({
				type: 'add',
			})
		}
	}

	//转账充值modal
	const TransferModalProps = {
		accountMsg,
		visible: true,
		handleCancel() {
			setVisible(undefined);
			dispatch({
				type: 'add'
			})
		},
	};

	//绑定银行卡
	const BankCardModalProps = {
		accountMsg,
		bankCardSwitch: true,
		pageInit() {
			getAccountInfo();
			setVisible(undefined);
		},
		//绑定银行卡弹窗关闭事件
		bankCardClose() {
			setVisible(undefined);
		},
	};

	const { hasPassword, bankNo, availBalance = 0, cashBalance = 0, openBankName } = accountDetail;

	//仓储用户状态下隐藏充值，提现三个按钮
	return (
		<div className={styles.container}>
			<div className={styles.amountSection}>
				<div className={styles.iconLeft}>
					<IconFont type="iconbalance" />
				</div>
				<div className={styles.textRight} >
					<span className={styles.flexBox}>
						<div className={styles.amountBox}>
							<div className={styles.amountItem}>
								可用余额：<span className={`${styles.banlance} common-color9`}>{canUseAmount ? formatAmount(Number(availBalance)) : "***"}</span> 元
								<span onClick={() => setCanUse(!canUseAmount)}>
									<IconFont type={canUseAmount ? "iconzhengyan" : "iconbiyan"} style={{ fontSize: 16, marginLeft: 6, cursor: 'pointer' }} />
								</span>
								{ 
									userType == 2 && (
										<div style={{ marginTop: 12 }}>
										{accountMsg.isUnionUser ? <Button style={{ marginRight: 30 }} onClick={() => commonRechargeClick('scanCharge')}>扫码充值</Button>
																							: <Button style={{ marginRight: 30 }} onClick={() => commonRechargeClick('normalCharge')}>普通充值</Button>}
											<Button onClick={()=>commonCheckAccountAndBank('applyCash')}>申请提现</Button>
										</div>
									)
								}
							</div>
							<div className={styles.amountItem}>
								提现待到账：<span className={`${styles.banlance} common-color2`}>{awaitAmount ? formatAmount(Number(cashBalance)) : "***"}</span> 元
								<span onClick={() => setAwait(!awaitAmount)}>
									<IconFont type={awaitAmount ? "iconzhengyan" : "iconbiyan"} style={{ fontSize: 16, marginLeft: 6, cursor: 'pointer' }} />
								</span>
								{userType == 2 && <div style={{ marginTop: 12 }}><Button onClick={()=>commonCheckAccountAndBank('transferCharge')}>转账充值</Button><span className='common-color9'>(免手续费)</span></div>}
							</div>
							<div className={styles.amountItem}>
							待结算金额：<span className={`${styles.banlance} common-color9`}>{pendingAmount ? formatAmount(computeShowAmount) : '***'}</span> 元
								<span onClick={() => setPending(!pendingAmount)}>
									<IconFont type={pendingAmount ? "iconzhengyan" : "iconbiyan"} style={{ fontSize: 16, marginLeft: 6 }} />
								</span>
							</div>
						</div>
					</span>
				</div>
			</div>
			<div className={styles.infoSection}>
				{/* <div className={styles.iconLeft}>
					<Avatar size={48} icon={<UserOutlined />} src={headImgUrl}></Avatar>
				</div> */}
				<div className={styles.textRight}>
					<span>
						<p style={{ margin: "4px 0" }}>
							支付密码设置(商户)：{hasPassword ? '已设置' : '未设置'}
							<span className="common-color1" style={{ cursor: "pointer", marginLeft: '12px' }} onClick={handlePasswordClick}>
								{hasPassword ? '修改' : '设置'}
							</span>
						</p>
						<p style={{ margin: "4px 0" }}>
							银行卡绑定(商户)：
							{bankNo &&  <span>{openBankName}-{bankNo.slice(bankNo.length-4)}</span>}
							<span className="common-color1" style={{ cursor: "pointer", marginLeft: '12px' }} onClick={handleClickBank}>
								{bankNo ? '解绑' : '去绑卡'}
							</span>
						</p>
						<p className="common-color9" style={{ fontSize: 12 }}>子账号不允许设置、修改支付密码</p>
					</span>
				</div>
			</div>

			{/* 绑定银行卡修改修改 */}
			{visible == 'updateBank' && <BankCardModal {...BankCardModalProps} />}

			{/* 支付密码修改 */}
			{visible == 'updatePassword' && <PayModal {...PayModalProps} />}

			{/* 普通充值 */}
			{visible == 'normalCharge' && <RechargeModal {...RechargeModalProps} />}

			{/* 扫码充值 */}
			{ visible == 'scanCharge' && <ScanRechargeModal {...ScanRechargeModalProps} /> }

			{/* 转账充值 */}
			{visible == 'transferCharge' && <TransferModal {...TransferModalProps} />}

			{/* {loading && <CommonLoading loading={true} />} */}
		</div>
	)
}

export default UserInfo;
